<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Focus & Log Tool</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@700&display=swap" rel="stylesheet">
    <style>
        /* --- Base Styles & Font --- */
        :root {
            --primary-bg: #f4f4f9;
            --secondary-bg: #ffffff;
            --text-color: #333;
            --accent-color: #007bff;
            --border-color: #ddd;
            --shadow-color: rgba(0, 0, 0, 0.1);
            --font-main: 'Nunito', sans-serif;
            --transition-curve: cubic-bezier(0.4, 0, 0.2, 1); /* Smooth ease-in-out */
            --transition-duration: 0.3s;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: var(--font-main);
            background-color: var(--primary-bg);
            color: var(--text-color);
            line-height: 1.6;
            padding: 20px;
            font-weight: 700; /* Bold as requested */
        }

        /* --- Layout Containers --- */
        .container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 25px;
            max-width: 1200px;
            margin: 0 auto;
        }

        .tool-section {
            background-color: var(--secondary-bg);
            padding: 25px;
            border-radius: 15px; /* Rounded corners */
            box-shadow: 0 4px 15px var(--shadow-color);
            transition: transform var(--transition-duration) var(--transition-curve),
                        box-shadow var(--transition-duration) var(--transition-curve);
        }

        .tool-section:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px var(--shadow-color);
        }

        h2 {
            margin-bottom: 20px;
            color: var(--accent-color);
            text-align: center;
        }

        /* --- Common Form Elements --- */
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 700;
        }

        input[type="text"],
        input[type="number"],
        input[type="datetime-local"],
        select,
        textarea {
            width: 100%;
            padding: 12px;
            margin-bottom: 15px;
            border: 1px solid var(--border-color);
            border-radius: 8px; /* Rounded inputs */
            font-family: var(--font-main);
            font-weight: 700;
            transition: border-color var(--transition-duration) var(--transition-curve),
                        box-shadow var(--transition-duration) var(--transition-curve);
        }

        input[type="text"]:focus,
        input[type="number"]:focus,
        input[type="datetime-local"]:focus,
        select:focus,
        textarea:focus {
            outline: none;
            border-color: var(--accent-color);
            box-shadow: 0 0 5px rgba(0, 123, 255, 0.3);
        }

        button {
            background-color: var(--accent-color);
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-family: var(--font-main);
            font-weight: 700;
            transition: background-color var(--transition-duration) var(--transition-curve),
                        transform var(--transition-duration) var(--transition-curve);
            display: inline-block; /* Fit content */
            margin-right: 10px; /* Spacing between buttons */
            margin-bottom: 10px;
        }

        button:hover {
            background-color: #0056b3;
            transform: translateY(-2px);
        }

        button:active {
             transform: translateY(0);
        }

        /* --- Study Logger Specific --- */
        #log-display {
            margin-top: 20px;
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            padding: 10px;
        }
        #log-display p {
             margin-bottom: 8px;
             font-size: 0.9em;
             border-bottom: 1px dashed var(--border-color);
             padding-bottom: 5px;
        }
         #log-display p:last-child {
             border-bottom: none;
         }


        /* --- Pomodoro Timer Specific --- */
        #timer-display {
            font-size: 3.5em; /* Large timer display */
            text-align: center;
            margin: 20px 0;
            font-weight: 700;
        }

        .timer-controls, .timer-settings {
            display: flex;
            flex-wrap: wrap; /* Allow wrapping on smaller screens */
            justify-content: center;
            gap: 10px; /* Spacing between controls/settings */
            margin-bottom: 15px;
        }

        .timer-settings label {
             margin-bottom: 5px; /* Smaller margin in settings row */
             flex-basis: 100%; /* Label takes full width initially */
             text-align: left;
        }
         .timer-settings input {
             flex-grow: 1; /* Inputs take available space */
             min-width: 60px; /* Minimum width for inputs */
             margin-bottom: 10px; /* Spacing below inputs */
         }

        /* --- Reminder Popup --- */
        #reminder-popup {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) scale(0.9);
            background-color: rgba(50, 50, 50, 0.9);
            color: white;
            padding: 30px 40px;
            border-radius: 15px;
            z-index: 1000;
            opacity: 0;
            pointer-events: none; /* Initially not interactive */
            transition: opacity var(--transition-duration) var(--transition-curve),
                        transform var(--transition-duration) var(--transition-curve),
                        filter var(--transition-duration) var(--transition-curve); /* Transition opacity, transform, and filter */
            filter: blur(10px); /* Start blurred */
            text-align: center;
            font-size: 1.5em;
        }

        #reminder-popup.show {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1);
            pointer-events: auto; /* Interactive when shown */
            filter: blur(0); /* Unblur when shown */
        }

        /* --- Minimalist Notes Specific --- */
        #notes-area {
            min-height: 200px; /* Decent starting height */
            resize: vertical; /* Allow vertical resize */
            background-color: #fafafa; /* Slightly different bg for notes */
            font-size: 1.1em;
            line-height: 1.7;
        }

    </style>
</head>
<body>

    <div class="container">

        <!-- Study Parameter Logger -->
        <div class="tool-section" id="logger-section">
            <h2>Study Log</h2>
            <form id="logger-form">
                <label for="subject">Subject:</label>
                <input type="text" id="subject" list="subject-options" placeholder="e.g., Math, Physics">
                <datalist id="subject-options">
                    <option value="Math">
                    <option value="Physics">
                    <option value="Chemistry">
                    <option value="Biology">
                    <option value="History">
                    <option value="Language Arts">
                    </datalist>

                <label for="task-type">Task Type:</label>
                <select id="task-type">
                    <option value="Reading">Reading</option>
                    <option value="Practice Problems">Practice Problems</option>
                    <option value="Review Notes">Review Notes</option>
                    <option value="Flashcards">Flashcards</option>
                    <option value="Watching Lecture">Watching Lecture</option>
                    <option value="Writing">Writing</option>
                </select>

                <label for="start-time">Start Time:</label>
                <input type="datetime-local" id="start-time">

                <label for="end-time">End Time:</label>
                <input type="datetime-local" id="end-time">

                <label for="focus-rating">Focus Rating (1-5):</label>
                <input type="range" id="focus-rating" min="1" max="5" value="3" style="cursor: pointer;">

                <label for="log-notes">Notes/Distractions:</label>
                <textarea id="log-notes" rows="3" placeholder="Any specific challenges or insights?"></textarea>

                <button type="button" onclick="captureStartTime()">Now</button> (Start)
                <button type="button" onclick="captureEndTime()">Now</button> (End)
                <button type="submit">Save Log Entry</button>
            </form>
            <div id="log-display">
                <h3>Recent Logs:</h3>
                <!-- Logs will be added here by JS -->
            </div>
            <button type="button" onclick="clearLogs()">Clear All Logs</button>
        </div>

        <!-- Pomodoro Timer -->
        <div class="tool-section" id="timer-section">
            <h2>Pomodoro Timer</h2>
            <div id="timer-display">25:00</div>
            <div class="timer-controls">
                <button id="start-pause-btn">Start</button>
                <button id="reset-btn">Reset</button>
            </div>
            <div class="timer-settings">
                <label for="work-duration">Work (min):</label>
                <input type="number" id="work-duration" value="25" min="1">

                <label for="rest-duration">Rest (min):</label>
                <input type="number" id="rest-duration" value="5" min="1">

                <label for="reminder-interval">Remind Every (min):</label>
                <input type="number" id="reminder-interval" value="5" min="1">

                 <label for="reminder-text">Reminder Text:</label>
                 <input type="text" id="reminder-text" value="Check Focus!">
            </div>
             <div id="reminder-popup">Reminder Text Goes Here</div>
        </div>

        <!-- Minimalist Notes -->
        <div class="tool-section" id="notes-section">
            <h2>Quick Notes / Questions</h2>
            <textarea id="notes-area" placeholder="Jot down thoughts, questions, or ideas here..."></textarea>
            <!-- Save happens automatically on input -->
        </div>

    </div>

    <script>
        // --- LocalStorage Keys ---
        const LOG_KEY = 'studyLogs';
        const NOTES_KEY = 'quickNotes';
        const TIMER_SETTINGS_KEY = 'timerSettings';

        // --- Study Logger Logic ---
        const loggerForm = document.getElementById('logger-form');
        const logDisplay = document.getElementById('log-display');
        const startTimeInput = document.getElementById('start-time');
        const endTimeInput = document.getElementById('end-time');

        function getCurrentDateTimeLocal() {
            const now = new Date();
            now.setMinutes(now.getMinutes() - now.getTimezoneOffset()); // Adjust for timezone
            return now.toISOString().slice(0, 16);
        }

        function captureStartTime() {
            startTimeInput.value = getCurrentDateTimeLocal();
        }

        function captureEndTime() {
            endTimeInput.value = getCurrentDateTimeLocal();
        }

        function loadLogs() {
            const logs = JSON.parse(localStorage.getItem(LOG_KEY) || '[]');
            logDisplay.innerHTML = '<h3>Recent Logs:</h3>'; // Clear previous entries
            // Display latest logs first
            logs.slice().reverse().forEach(log => {
                const p = document.createElement('p');
                const start = log.start ? new Date(log.start).toLocaleString() : 'N/A';
                const end = log.end ? new Date(log.end).toLocaleString() : 'N/A';
                p.innerHTML = `<strong>${log.subject || 'N/A'}</strong> (${log.task || 'N/A'})
                             <br>Focus: ${log.focus}/5 | ${start} - ${end}
                             ${log.notes ? `<br><em>Note: ${log.notes}</em>` : ''}`;
                logDisplay.appendChild(p);
            });
        }

        function clearLogs() {
            if (confirm('Are you sure you want to delete all logs? This cannot be undone.')) {
                 localStorage.removeItem(LOG_KEY);
                 loadLogs(); // Refresh display
            }
        }


        loggerForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const newLog = {
                subject: document.getElementById('subject').value,
                task: document.getElementById('task-type').value,
                start: startTimeInput.value,
                end: endTimeInput.value,
                focus: document.getElementById('focus-rating').value,
                notes: document.getElementById('log-notes').value,
                timestamp: Date.now()
            };

            const logs = JSON.parse(localStorage.getItem(LOG_KEY) || '[]');
            logs.push(newLog);
            localStorage.setItem(LOG_KEY, JSON.stringify(logs));

            loadLogs(); // Refresh display
            loggerForm.reset(); // Clear form
             startTimeInput.value = ''; // Clear datetime inputs specifically
             endTimeInput.value = '';
        });

        // --- Minimalist Notes Logic ---
        const notesArea = document.getElementById('notes-area');

        function loadNotes() {
            notesArea.value = localStorage.getItem(NOTES_KEY) || '';
        }

        notesArea.addEventListener('input', () => {
            localStorage.setItem(NOTES_KEY, notesArea.value);
        });

        // --- Pomodoro Timer Logic ---
        const timerDisplay = document.getElementById('timer-display');
        const startPauseBtn = document.getElementById('start-pause-btn');
        const resetBtn = document.getElementById('reset-btn');
        const workDurationInput = document.getElementById('work-duration');
        const restDurationInput = document.getElementById('rest-duration');
        const reminderIntervalInput = document.getElementById('reminder-interval');
        const reminderTextInput = document.getElementById('reminder-text');
        const reminderPopup = document.getElementById('reminder-popup');

        let timerIntervalId = null;
        let reminderTimeoutId = null;
        let currentTime = 0; // in seconds
        let totalWorkSeconds = 0; // Keep track for reminders
        let isWorkTime = true;
        let isPaused = true;

        function loadTimerSettings() {
             const settings = JSON.parse(localStorage.getItem(TIMER_SETTINGS_KEY) || '{}');
             workDurationInput.value = settings.workDuration || 25;
             restDurationInput.value = settings.restDuration || 5;
             reminderIntervalInput.value = settings.reminderInterval || 5;
             reminderTextInput.value = settings.reminderText || 'Check Focus!';
             resetTimer(); // Initialize display based on loaded settings
        }

         function saveTimerSettings() {
             const settings = {
                 workDuration: workDurationInput.value,
                 restDuration: restDurationInput.value,
                 reminderInterval: reminderIntervalInput.value,
                 reminderText: reminderTextInput.value,
             };
             localStorage.setItem(TIMER_SETTINGS_KEY, JSON.stringify(settings));
         }

        // Add event listeners to save settings when changed
        workDurationInput.addEventListener('change', saveTimerSettings);
        restDurationInput.addEventListener('change', saveTimerSettings);
        reminderIntervalInput.addEventListener('change', saveTimerSettings);
        reminderTextInput.addEventListener('change', saveTimerSettings);


        function formatTime(seconds) {
            const mins = Math.floor(seconds / 60);
            const secs = seconds % 60;
            return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
        }

        function updateDisplay() {
            timerDisplay.textContent = formatTime(currentTime);
            document.title = `${formatTime(currentTime)} - ${isWorkTime ? 'Work' : 'Rest'}`; // Update browser tab title
        }

         function showReminder() {
             if (!isWorkTime || isPaused) return; // Only remind during active work session

             reminderPopup.textContent = reminderTextInput.value || "Check Focus!";
             reminderPopup.classList.add('show');

             // Hide reminder after a few seconds
             setTimeout(() => {
                 reminderPopup.classList.remove('show');
             }, 3000); // Show for 3 seconds

             // Schedule the next reminder
             scheduleNextReminder();
         }

         function scheduleNextReminder() {
              // Clear any existing reminder timeout
             clearTimeout(reminderTimeoutId);

             if (!isWorkTime || isPaused) return; // Don't schedule if not working or paused

             const intervalMinutes = parseInt(reminderIntervalInput.value, 10);
             if (isNaN(intervalMinutes) || intervalMinutes <= 0) return; // Invalid interval

            // Calculate remaining seconds until the next reminder interval *within the current work session*
            const intervalSeconds = intervalMinutes * 60;
            const elapsedWorkSeconds = totalWorkSeconds - currentTime; // Seconds passed in current work session
            const nextReminderPoint = Math.ceil((elapsedWorkSeconds + 1) / intervalSeconds) * intervalSeconds; // Find the next interval boundary
            let secondsUntilNextReminder = nextReminderPoint - elapsedWorkSeconds;

             // Ensure reminder doesn't fire after the work session ends
             if (secondsUntilNextReminder > 0 && secondsUntilNextReminder <= currentTime) {
                reminderTimeoutId = setTimeout(showReminder, secondsUntilNextReminder * 1000);
             }
         }


        function tick() {
            if (isPaused) return;

            currentTime--;

            if (currentTime < 0) {
                // Switch phase
                isWorkTime = !isWorkTime;
                currentTime = (isWorkTime ? parseInt(workDurationInput.value, 10) : parseInt(restDurationInput.value, 10)) * 60;
                totalWorkSeconds = isWorkTime ? currentTime : 0; // Reset work seconds counter on new work session
                alert(isWorkTime ? "Rest over! Time to work." : "Work session over! Time for a break.");
                // Automatically start next phase? Optional. Current setup requires manual start after alert.
                // Or simply update display and pause:
                 pauseTimer(); // Pause after switching phases
                 updateDisplay();
                 startPauseBtn.textContent = 'Start';
                 if (isWorkTime) scheduleNextReminder(); // Schedule reminder for the new work phase if it starts
                 return; // Stop tick execution for this cycle
            }

             updateDisplay();
        }


        function startTimer() {
             if (timerIntervalId) clearInterval(timerIntervalId); // Clear existing interval if any
             isPaused = false;
             startPauseBtn.textContent = 'Pause';
             timerIntervalId = setInterval(tick, 1000);
             if (isWorkTime) {
                  if (currentTime === totalWorkSeconds) { // Only schedule first reminder if starting fresh
                       scheduleNextReminder(); // Schedule the *first* reminder
                  } else {
                       // If resuming, the existing reminder timeout should continue or be rescheduled
                       scheduleNextReminder(); // Recalculate and schedule reminder on resume
                  }
             } else {
                  clearTimeout(reminderTimeoutId); // No reminders during rest
             }
        }

        function pauseTimer() {
             isPaused = true;
             startPauseBtn.textContent = 'Resume';
             clearInterval(timerIntervalId);
             clearTimeout(reminderTimeoutId); // Clear reminder timeout on pause
        }

        function resetTimer() {
            clearInterval(timerIntervalId);
            clearTimeout(reminderTimeoutId);
            isPaused = true;
            isWorkTime = true; // Default to work time on reset
            currentTime = parseInt(workDurationInput.value, 10) * 60 || 25 * 60;
            totalWorkSeconds = currentTime; // Set total for reminder calc
            startPauseBtn.textContent = 'Start';
            updateDisplay();
        }

        startPauseBtn.addEventListener('click', () => {
            if (isPaused) {
                 // If current time is 0, reset based on phase before starting
                 if (currentTime <= 0) {
                      currentTime = (isWorkTime ? parseInt(workDurationInput.value, 10) : parseInt(restDurationInput.value, 10)) * 60;
                      totalWorkSeconds = isWorkTime ? currentTime : 0;
                      updateDisplay();
                 }
                 startTimer();
            } else {
                pauseTimer();
            }
        });

        resetBtn.addEventListener('click', resetTimer);


        // --- Initial Load ---
        document.addEventListener('DOMContentLoaded', () => {
            loadLogs();
            loadNotes();
            loadTimerSettings(); // This will call resetTimer internally
        });

    </script>

</body>
</html>
